package com.ltu.ai.sparkdesk.websocket.iat;

import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;
import java.util.Locale;
import java.util.Objects;
import java.util.TimeZone;
import java.util.concurrent.CountDownLatch;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.java_websocket.WebSocket;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft;
import org.java_websocket.enums.ReadyState;
import org.java_websocket.handshake.ServerHandshake;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ltu.ai.sparkdesk.websocket.AiContextManager;
import com.ltu.ai.sparkdesk.websocket.AiContextManager.IatContext;
import com.ltu.ai.sparkdesk.websocket.legal.LegalSocketService;
import com.ltu.ai.sparkdesk.websocket.ultra.SparkSocketService;
import com.ltu.domain.mp_entity.customize.DeviceEntity;
import com.ltu.domain.mp_entity.customize.SessionInfoEntity;
import com.ltu.service.OssService;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import okhttp3.HttpUrl;



@Slf4j
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Component
public class IatSocketService{
	
    private final IatSendHandle iatSendHandle;
    private final AiContextManager aiContextManager;
    private final  SparkSocketService  sparkSocketService;
//    private final  SparkSocketService  legalSocketService;
    // 语音识别成文字
 	private static final String IAT_HOST = "iat-api.xfyun.cn/v2/iat";
 	private static final String HostUrl = "https://";
 	
 

    public void  createIatClient(String filePath,String deviceMac) {
		try {
			IatContext iatContext =	AiContextManager.IatContextMap.get(deviceMac);
			if(iatContext.getIatClient()!=null) {
				iatContext.getIatClient().close();
				iatContext.setIatClient(null);
				log.error("设备：{}，重入问题",deviceMac);
				if(iatContext.getSparkSocketClient()!=null && iatContext.getSparkSocketClient().isOpen()){
					iatContext.getSparkSocketClient().close();
					iatContext.setSparkSocketClient(null);
					if(iatContext.getSessionEntity()!=null && iatContext.getSessionEntity().getTotalQuestion()>0)
						iatContext.getSessionEntity().setTotalQuestion( iatContext.getSessionEntity().getTotalQuestion()-1);
				}
			}
			
			String authUrl = AiContextManager.getAuthUrl(HostUrl + IAT_HOST);
				String url = authUrl.toString().replace("http://", "ws://").replace("https://", "wss://");
				URI	serverUri = new URI(url);
			if(iatContext.getSessionEntity() == null) {
				SessionInfoEntity sessionEntity =	aiContextManager.createSessionEntity( iatContext.getDeviceEntity());
				iatContext.setSessionEntity(sessionEntity);
			}
				
			iatContext.setFilePath(filePath);
	    	IatSocketClient  client = new  IatSocketClient(serverUri, aiContextManager,iatContext,iatSendHandle,sparkSocketService);
	    	client.connect();
	    	iatContext.setIatClient(client);
//	        while (!client.getReadyState().equals(ReadyState.OPEN)) {
//                System.out.println(getCurrentTimeStr() + "\t IAT连接中");
//                Thread.sleep(1000);
//            }
//	        //打开语音文件持续发送语音二进制流
//	        iatSendHandle.sendData(client,iatContext.getFilePath());
	        
		} catch (URISyntaxException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	
    }
    
   
}